import { initSystem, logout } from '@/helper/system';
import { useGlobalStore } from '@common/store/global-store';
import { useMenuStore } from '@/stores/menu-store';
import { GlobalSettingsEnum } from '@common/helper/constant';
import { isArray } from '@jecloud/utils';
import { thirdRouterGuard, isThirdLogin } from '@/helper/third';
const { GLOBAL_SETTINGS_TOKENKEY: tokenKey } = GlobalSettingsEnum;

export function createRouterGuard(router) {
  const whiteRoutes = ['Login', 'PlanLogin', 'ThirdLogin', 'PreviewMarkdown', 'PreviewFile'];
  const globalStore = useGlobalStore();
  const menuStore = useMenuStore();
  router.beforeEach((to, from, next) => {
    const { plan } = to.params || {};
    // 激活方案
    plan && (globalStore.activePlan = plan);

    // 地址栏切换方案
    if (from.params?.plan && from.params?.plan !== to.params?.plan) {
      window.location.reload();
    } else if (to.name === tokenKey) {
      // token路由认证
      const { token, redirect } = to.params;
      // 设置token
      if (token) {
        globalStore.setToken(token);
      }
      // 重置选中菜单
      menuStore.resetSelectMenu();
      // 认证后的跳转路径
      const path = isArray(redirect) ? redirect.join('/') : redirect;
      next({ path: `/${path}`, query: to.query });
    } else if (isThirdLogin(to.query)) {
      // 三方登录，临时授权码
      thirdRouterGuard(to, from, next);
    } else if (whiteRoutes.includes(to.name)) {
      // 路由白名单
      next();
    } else {
      // 增加系统登录成功标识
      if (from.path === '/' || whiteRoutes.includes(from.name)) {
        to.meta.loginSuccess = true;
      }
      // token参数认证
      const token = to.query[tokenKey];
      token && globalStore.setToken(token);

      // 初始化系统数据
      initSystem(router, to)
        .then(() => {
          next();
        })
        .catch((error) => {
          console.error(error);
          logout();
        });
    }
  });

  return false;
}
